<template>
  <div class="container">
    <div ref="cardRef">
      <el-card shadow="never">
        <div class="edit-btn" v-if="counter.isShowActionBtn(info)" @click="proxy.$refs.updateClassRef.open(info)">
          <el-button type="primary">编辑班级信息</el-button>
        </div>

        <div class="title">{{info.className}}
          <span v-if="info.classId">{{info.classId}}</span>
        </div>

        <div v-loading="loading">
          <div class="row">
            <div class="col" :style="{ width: firstColWidth + 'px' }">开班时间：{{info.classOpeningTime}}</div>
            <div class="col flex" :style="colStyle">授课地点：<dictSelect readonly="1" v-model="info.classAddress" dictCode="teaching_location"></dictSelect>
            </div>
            <div class="col" :style="colStyle">班级课时：{{info.classHours}}</div>
            <div class="col flex" :style="colStyle">班级状态：
              <div v-if="info.status == 0" style="color: #E99D42">待开班</div>
              <div v-else-if="info.status == 1" style="color: #54C076">开班</div>
              <div v-else style="color: #909399">结业</div>
            </div>
            <div class="col" :style="colStyle">鉴定人数：{{peopleParams.numberAppraisers}}</div>
          </div>

          <div class="row">
            <div class="col flex" :style="{ width: firstColWidth + 'px' }">班级人数：{{classStudentsNum}}
              <div class="button">（{{actual_number}}）</div>
            </div>
            <div class="col" :style="colStyle">授课讲师：{{teachingTeachers||info.teachingTeacher}}</div>
            <div class="col" :style="colStyle">排班课时：{{classCurrentHours}} / {{info.classHours}}</div>
            <div class="col" :style="colStyle">已授课时：{{lessonHours_format(lessonHours)}} / {{classCurrentHours}}</div>
            <div class="col" :style="colStyle">获证人数：{{trainingResultResult.certifiedNum}}</div>
          </div>

          <div class="row" style="margin-bottom: 0 !important;">
            <div class="col flex shrink" ref="firstCol">
              关联课程：<courseQuery v-model="info.curriculumId" readonly="1"></courseQuery>
            </div>
            <div class="col flex" :style="colStyle">
              班级老师：<accountSelect v-model="info.classTeacherId" readonly="1"></accountSelect>
            </div>
            <div class="col" :style="colStyle">
              排班天数：{{allTeachingSchedule.length}}
            </div>
            <div class="col" :style="colStyle">已授节数：{{lessonHours.length}} / {{allTeachingSchedule.length}}</div>
            <div class="col" :style="colStyle">鉴定合格率：{{qualificationRate}}%</div>
          </div>
        </div>

        <updateClass ref="updateClassRef" @fatherMethod="getInfo"></updateClass>
      </el-card>
    </div>

    <el-card shadow="never" class="classCard">
      <div class="flex justifyBetween">
        <el-tabs v-model="activeName" class="class-tabs">
          <el-tab-pane :label="item.name" :name="item.value.toString()" v-for="(item,index) in tabs" :key="index"></el-tab-pane>
        </el-tabs>
        <!-- && counter.isLocalhost -->
        <el-button type="primary" plain v-if="activeName==4" @click="proxy.$refs.inputFile.click()">上传班级管理手册模板</el-button>
        <el-button type="primary" plain v-if="activeName==4" @click="counter.downLoadTemplate('classManagementManual','班级管理手册模板')">下载班级管理手册模板</el-button>
        <el-button type="primary" :loading="exportLoading" plain v-if="activeName==4" @click="exportAll">导出班级管理手册</el-button>

        <!-- 教务管理手册 -->
        <el-button type="primary" plain v-if="activeName==5" @click="proxy.$refs.inputFile.click()">上传教务管理手册模板</el-button>
        <el-button type="primary" plain v-if="activeName==5" @click="counter.downLoadTemplate('eduAdminManual','教务管理手册模板')">下载教务管理手册</el-button>
        <el-button type="primary" plain v-if="activeName==5" @click="exportAcademic">导出教务管理手册</el-button>

        <!-- 收款凭证模板 -->
        <el-button type="primary" plain v-if="activeName==7" @click="proxy.$refs.inputFile.click()">上传收款凭证模板</el-button>
        <el-button type="primary" plain v-if="activeName==7" @click="counter.downLoadTemplate('receiptVoucher','收款凭证模板')">下载收款凭证模板</el-button>
        <el-button type="primary" :disabled="receiptVoucherList.length==0" plain v-if="activeName==7" @click="proxy.$refs.receiptVoucherRef.exportWord()">下载收款凭证</el-button>
      </div>
      <!-- 排课信息 -->
      <teachingScheduleData :info="info" @fatherMethod="getInfo" v-if="activeName==1"></teachingScheduleData>
      <!-- 班级学员 -->
      <classStudents :info="info" v-else-if="activeName==2"></classStudents>
      <!-- 签到情况 -->
      <classSignIn :info="info" v-else-if="activeName==3"></classSignIn>
      <!-- 教务管理手册 -->
      <academicManageManual :info="info" v-else-if="activeName==5" :archiveBinding="archiveBinding"></academicManageManual>
      <!-- 班级管理手册 -->
      <classManagementManual :info="info" v-else-if="activeName==4" :archiveBinding="archiveBinding"></classManagementManual>
      <!-- 班级相册 -->
      <classAlbum :info="info" v-else-if="activeName==6"></classAlbum>
      <!-- 收款凭证 -->
      <receiptVoucher ref="receiptVoucherRef" :info="info" v-else-if="activeName==7" @fatherMethod="getReceiptVoucherList"></receiptVoucher>
      <!-- 考试管理 -->
      <certificationManage v-else-if="activeName==8" :info="info"></certificationManage>
    </el-card>

    <input type="file" @change="handleFileUpload" v-show="false" ref="inputFile" />
  </div>
</template>

<script setup lang="ts">
// 考试管理
import certificationManage from "@/views/courseManage/components/certificationManage.vue";
//收款凭证
import receiptVoucher from "@/views/courseManage/components/receiptVoucher.vue";
//班级相册
import classAlbum from "@/views/courseManage/components/classAlbum.vue";
import updateClass from "@/views/courseManage/components/updateClass.vue";
//教务管理手册
import academicManageManual from "@/views/courseManage/components/academicManageManual.vue";
// 排课信息
import teachingScheduleData from "@/views/courseManage/components/teachingScheduleData.vue";
//班级学员
import classStudents from "@/views/courseManage/components/classStudents.vue";
//签到情况
import classSignIn from "@/views/courseManage/components/classSignIn.vue";
//班级管理手册
import classManagementManual from "@/views/courseManage/components/classManagementManual.vue";
import { useRoute } from "vue-router";
const route = useRoute();
const { proxy } = getCurrentInstance();
import useCounterStore from "@/store/counter";
const counter = useCounterStore();

let info = ref({});
let activeName = ref("1");
let firstColWidth = ref(0); //最长的宽度
let loading = ref(false);
let teachingTeachers = ref("");
let classStudentsNum = ref(0);
let actual_number = ref(0); //报送人社人数
let teachingSchedule = ref([]);
let classCurrentHours = ref(0); //排课课时
let lessonHours = ref([]); //已授课时
let allTeachingSchedule = ref([]); //全部排课
let archiveBinding = ref([]); //绑定的档案
let templateUrl; //模板下载地址
let exportLoading = ref(false);
let trainingResultResult = ref({}); //培训结果
let receiptVoucherList = ref([]);
let peopleParams = ref({}); //鉴定人数等参数

//班级标签
let tabs = computed(() => {
  let { classTabs } = info.value;
  if (classTabs && classTabs.length) {
    let list = [];
    counter.classTabs.forEach((element) => {
      if (classTabs.includes(element.value)) {
        list.push(element);
      }
    });
    return list;
  } else {
    return counter.classTabs;
  }
});

let classId = computed(() => {
  return route.query.classId;
});

let qualificationRate = computed(() => {
  let a = peopleParams.value["numberAppraisers"] || 0;
  let b = trainingResultResult.value["certifiedNum"] || 0;
  return ((b / a) * 100).toFixed(2);
});

let colStyle = computed(() => {
  if (firstColWidth.value) {
    return {
      width: `calc((100% - ${firstColWidth.value}px - 100px)/4)`,
    };
  }
});

onMounted(() => {
  getTemplateUrl();
  getInfo();
  getBindArchives();
  if (route.query.current) activeName.value = route.query.current;
});

function getReceiptVoucherList(e) {
  receiptVoucherList.value = e;
}

async function handleFileUpload(event) {
  try {
    const files = event.target.files;
    let type;
    if (activeName.value == 4) {
      type = "classManagementManual";
    } else if (activeName.value == 7) {
      //收款凭证
      type = "receiptVoucher";
    } else if (activeName.value == 5) {
      //教务管理手册
      type = "eduAdminManual";
    }
    counter.importTemplate(files, type);
    getTemplateUrl();
  } catch (error) {
  } finally {
    event.target.value = "";
  }
}

async function getTemplateUrl() {
  templateUrl = await proxy.$apis.fileTemplate({
    data: { type: "classManagementManual" },
    type: "downLoad",
  });
}

function lessonHours_format(list) {
  let amount = 0;
  list.forEach((element) => {
    amount += element.unitClassHours;
  });
  return amount;
}

//绑定的档案
async function getBindArchives() {
  archiveBinding.value = await proxy.$apis.classData({
    type: "relatedArchives",
    data: { classId: classId.value },
  });
  console.log("绑定的档案", archiveBinding.value);
}

async function getClass() {
  info.value = await proxy.$apis.classData({
    type: "details",
    data: { _id: classId.value },
  });
  console.log("班级信息", info.value);
}

async function getInfo() {
  try {
    loading.value = true;
    await getClass();
    setCss();
    //班级人数
    let classStudentsList = await proxy.$apis.classStudent({
      type: "query",
      data: { classId: classId.value },
    });
    console.log("班级学员", classStudentsList);
    let numberAppraisers = 0;
    actual_number.value = 0;
    classStudentsList.forEach((element) => {
      if (
        element.declarationBatchNumber &&
        element.theory &&
        element.practicalTraining
      ) {
        numberAppraisers++;
      }
      if (element.isSubmit) actual_number.value++; //报送人社人数
    });
    peopleParams.value["numberAppraisers"] = numberAppraisers; //鉴定人数
    classStudentsNum.value = classStudentsList.length;

    //全部排课
    let arr = await proxy.$apis.teachingScheduleData({
      type: "query",
      data: { classId: classId.value },
    });
    let teachers = [];
    arr.forEach((element) => {
      teachers.push(element.teachingTeacher);
    });
    teachingTeachers.value = proxy.$utils.unique(teachers).toString();
    //console.log("全部排课", arr);
    allTeachingSchedule.value = [...arr];

    //排课课时
    classCurrentHours.value = 0;
    arr.forEach((element) => {
      classCurrentHours.value += element.unitClassHours;
    });

    //已授课时
    lessonHours.value = await proxy.$apis.teachingScheduleData({
      type: "lessonHours",
      data: { classId: classId.value },
    });

    //培训结果
    trainingResultResult.value = await counter.trainingResultExportParams(
      classId.value
    );
  } catch (error) {
    console.log("error", error);
  } finally {
    nextTick(() => {
      counter.classCardHeight = proxy.$refs.cardRef.offsetHeight;
    });
    loading.value = false;
  }
}

function setCss() {
  nextTick(() => {
    firstColWidth.value = proxy.$refs.firstCol.offsetWidth;
  });
}

async function exportAll() {
  try {
    exportLoading.value = true;
    if (!templateUrl) return proxy.$utils.showToast("模板下载地址为空", 0);
    let params = {
      classId: info.value["classId"] ? info.value["classId"] : "",
      occupationalLevel: `${info.value["occupational"]}(${info.value["level"]})`,
      occupational: info.value["occupational"],
      level: info.value["level"],
      teachingTeacher: teachingTeachers.value || info.value["teachingTeacher"],
      classOpeningTime: info.value["classOpeningTime"],
    };
    //账号
    let accounts = await proxy.$apis.account({
      type: "query",
    });
    let index = proxy.$utils.findIndexByField(
      accounts,
      "_id",
      info.value["classTeacherId"]
    );
    if (index != -1) params["classTeacher"] = accounts[index]["userName"];

    //课程安排表
    let course = await counter.courseRankingTable(classId.value);
    params["courses"] = await counter.courseCreateExportParams(
      course.tableData
    );
    //学员信息表
    let students = await counter.studentInfo(classId.value);
    params["students"] = await counter.studentExportParams(students);
    //授课计划表
    let teachingPlanResponse = await counter.getTeachingPlan(classId.value);
    let teachingPlanParasm = await counter.teachingPlanExportParams(
      teachingPlanResponse.tableData,
      teachingPlanResponse.archiveBindingList,
      classId.value
    );
    params["teachingPlans"] = teachingPlanParasm.list;
    params["llTotal"] = teachingPlanParasm.llTotal;
    params["sxTotal"] = teachingPlanParasm.sxTotal;
    params["requirement"] = teachingPlanParasm.requirement;
    params["aKey"] = teachingPlanParasm.aKey;
    params["difficulty"] = teachingPlanParasm.difficulty;
    params["afterword"] = teachingPlanParasm.afterword;
    //教案
    let lessonPlan = await counter.getTeachingPlan(classId.value);
    params["lessonPlans"] = await counter.lessonPlanExportParams(
      lessonPlan.tableData,
      lessonPlan.archiveBindingList,
      classId.value
    );
    let classOpeningTime = info.value["classOpeningTime"];
    let dateWriting = proxy.$utils.getPreMonth(classOpeningTime);
    params["lessonPlansYear"] = proxy.$utils.dateTimeFormateFn(
      dateWriting,
      "year"
    );
    params["lessonPlansMonth"] = proxy.$utils.dateTimeFormateFn(
      dateWriting,
      "month"
    );
    params["lessonPlansDay"] = proxy.$utils.dateTimeFormateFn(
      dateWriting,
      "day"
    );
    //教案附表
    params["lessonPlanAppendixTable"] =
      await counter.lessonPlanAppendixExportParams(classId.value);
    //教学日志
    params["teachingLogTable"] = await counter.teachingLogExportParams(
      teachingPlanResponse.tableData,
      teachingPlanResponse.archiveBindingList,
      classId.value
    );
    //授课计划审批
    let classDates = info.value["classDates"];
    let teachingPlanApproval = [];
    classDates.forEach((element) => {
      teachingPlanApproval.push({
        year: proxy.$utils.dateTimeFormateFn(element, "year"),
        month: proxy.$utils.dateTimeFormateFn(element, "month"),
        day: proxy.$utils.dateTimeFormateFn(element, "day"),
      });
    });
    params["teachingPlanApproval"] = teachingPlanApproval;
    //评议表
    let res = await counter.collegeEvaluationExportParams(classId.value);
    params["collegeEvaluationTable"] = res.data;

    //学院评议汇总
    params["suggestionsOpinions"] = res.suggestionsOpinions;
    let collegeEvaluationSummary = await proxy.$apis.classReport({
      data: { classId: classId.value },
      type: "student-evaluate-summary",
    });
    for (let key in collegeEvaluationSummary) {
      params[key] = collegeEvaluationSummary[key];
    }

    //培训结果
    let trainingResult = await counter.trainingResultExportParams(
      classId.value
    );
    for (let key in trainingResult) {
      params[key] = trainingResult[key];
    }

    //学员花名册
    let studentRoster = await counter.studentRosterExportParams(classId.value);
    //console.log("花名册参数", studentRoster);
    params["studentRoster"] = studentRoster.list;

    //班级管理手册导出的参数
    //return console.log("params", params);

    let url = await proxy.$apis.classDocExport({
      templateURL: templateUrl,
      data: params,
      fileName: "班级管理手册.docx",
    });
    window.location.href = url;
  } catch (error) {
    console.log("error", error);
  } finally {
    exportLoading.value = false;
  }
}

//教务导出
async function exportAcademic() {
  let res = await proxy.$apis.classLessonEvaluation({
    type: "details",
    data: { classId: info.value["_id"] },
  });
  let templateLink = await proxy.$apis.fileTemplate({
    data: { type: "eduAdminManual" },
    type: "downLoad",
  });
  let params = {
    year: proxy.$utils.dateTimeFormateFn(res.date, "year"),
    month: proxy.$utils.dateTimeFormateFn(res.date, "month"),
    day: proxy.$utils.dateTimeFormateFn(res.date, "day"),
    ...res,
  };
  let url = await proxy.$apis.classDocExport({
    templateURL: templateLink,
    data: params,
    fileName: "教务管理手册.docx",
  });
  window.location.href = url;

  let _id = archiveBinding.value[0]._id;
  let resp = await proxy.$apis.teachingArchives({
    type: "details",
    data: { _id },
  });
  let obj = {
    arr: [],
    fileName: `${resp.lecturerName}-附件`,
  };
  let keys = [
    { type: "file", name: "教师业务档案" },
    { type: "diplomaFile", name: "教师毕业证" },
    { type: "eduAuthFile", name: "学信网认证报告" },
    { type: "teacherAuthFile", name: "教师从业资格证" },
    { type: "skillCertificateFile", name: "职业技能证书" },
  ];
  for (let index = 0; index < keys.length; index++) {
    const element = keys[index];
    if (resp.hasOwnProperty(element.type) && resp[element.type]) {
      resp[element.type].forEach((item) => {
        obj.arr.push({
          path: item.path,
          name: `${resp.lecturerName}-${element.name}`,
        });
      });
    }
  }
  proxy.$utils.JSZipDownLoad(obj.arr, obj.fileName);
}

provide("getClassInfo", getClass);
</script>


<style lang="scss">
.class-tabs {
  width: 100%;
  .el-tabs__nav-wrap::after {
    background-color: transparent !important;
  }
}
</style>
<style lang="scss" scoped>
.container {
  margin: 0px;
  .title {
    color: #c95b18;
    font-weight: bold;
    font-size: 20px;
    margin-bottom: 20px;
    span {
      color: #4196a2;
      font-size: 16px;
      margin-left: 15px;
    }
  }
  .row {
    display: flex;
    align-items: center;
    font-size: 14px;
    justify-content: space-between;
    //font-weight: bold;
    margin-bottom: 10px;
    .col {
      text-align: left;
    }
  }
  .el-card {
    margin-bottom: 10px;
    position: relative;
    .edit-btn {
      position: absolute;
      top: 15px;
      right: 20px;
    }
  }
  ::v-deep .classCard {
    .el-card__body {
      padding: 15px 20px 0px 20px !important;
    }
  }
}
</style>